// index.js
import api from '../../utils/api'

Page({
  data: {
    userInfo: {
      avatarUrl: '../../pages/assets/img/tx.png',
      nickName: '微信用户',
    },
    iphone: '',
    radio: false
  },
  async onLoad() {
    const user = wx.getStorageSync('user');
    if (user.openid) {
      api.queryByOpenId({
        openId: user.openid
      }).then((e) => {
        console.log(e)
        if (e.isSuccess) {
          wx.switchTab({
            url: '/pages/home/home',
          })
        } else {
          this.getUserProfile()
        }

      })
    } else {
      this.getUserProfile()
    }

  },
  onChooseAvatar(e) {
    console.log(e, 555)
    const {
      avatarUrl
    } = e.detail
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res, 55)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onInput: function (e) {
    this.setData({
      iphone: e.detail.value
    })
  },
  radioChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      radio: true
    })
  },
  showUser() {
    wx.navigateTo({
      url: "/pages/protocol/protocol",
    })
  },
  showHome() {
    if (!this.data.iphone.trim()) {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
      });
      return;
    } else {
      if (!/^1[3456789]\d{9}$/.test(this.data.iphone)) {
        wx.showToast({
          title: '手机号格式错误',
          icon: 'none',
        });
        return;
      }
    }


    if (!this.data.radio) {
      wx.showToast({
        title: '请阅读并选择同意',
        icon: 'none',
      });
      return;
    }
    let that = this


    // //获取到你的openid
    wx.login({
      async success(res) {
        wx.request({
          //secret 3303ea795a19bdf3355ac352ca1eda38
          url: 'https://service-prkchobw-1258374330.gz.tencentapigw.com.cn/release/wechat-forworad?jsCode=' + res.code,
          success: (res) => {
            console.log(res.data, 666)
            if (!res.data.openid) {
              wx.showToast({
                title: '未获取到openid',
                icon: 'none',
              });
            } else {
              var obj = {};
              obj.openid = res.data.openid;
              obj.iphone = that.data.iphone
              //存储openid
              wx.setStorageSync('user', obj);
              //获取到你的openid
              console.log(obj.openid);
              api.login({
                openId: obj.openid,
                phoneNumber: that.data.iphone
              }).then(() => {
                wx.switchTab({
                  url: '/pages/home/home',
                })
              })
            }

          }
        })
      },
    })

  },
})